import * as types from './mutation-types'
import call from '../../api/call'
import {getCache} from '../../actions'
import m7dicMap from '@utils/m7dicMap.js'
import * as globalTypes from '../../mutation-types'
import customerApi from '../../api/customer'
import userApi from '../../api/user'
import { encrypt, getAesEncrypt} from '@/utils/m7Utils'
import { ElementUI } from '@/utils/commonJs/initElement.js'
import {formatShortTime, millsToDate, getCacheByKey, checkHideTel, getCallTimeLength, m7Language} from '@/utils/m7Utils'
export const queryMyLatestCdr  = ({commit, state, rootState, dispatch}, searchCondition) => { // 电话条查询最近5条的数据
  return call.queryMyLatestCdr(searchCondition).then(response => {
    return response
  }).catch((e) => {
    console.log(e)
  })
}

export const queryCallList = ({commit, state, rootState, dispatch}, searchCondition) => { // 查询通话列表数据
  if (searchCondition.type === 'cdr_call') { // 若是来电模块，返回vuex中的数据
    return Promise.resolve(state.callList.cdr_call)
  } else if (searchCondition.type === 'cdr_outbound') {
    return Promise.resolve(state.callList.cdr_outbound)
  }
  let type = searchCondition.type
  let phoneBarFlag = searchCondition.phoneBar // 软电话外呼按钮触发的action不往vuex里面存值，避免修改了通话列表里面的数据
  let searchCount = searchCondition.searchAllCount
  let autoqc = searchCondition.autoqc
  delete searchCondition.phoneBar
  delete searchCondition.searchAllCount
  delete searchCondition.type
  delete searchCondition.autoqc
  return call.queryCallList(searchCondition)
    .then(
      response => {
        if (response.success) {
          if (Object.keys(searchCondition).length === 1 && searchCondition.CALL_SHEET_ID) {
            return response
          } else if (!phoneBarFlag && !searchCount) { // 不是电话条外呼 && 查询count总数触发的action
            commit(types.QUERY_CALL_LIST, {data: response, type}) // 存储查询到的通话列表：来电，待处理，全部
            if (autoqc) { // 点击质检提醒跳转通话
              return response
            }
          } else if (searchCount) { // 通话查询count总数
            return response
          } else {
            return response.list
          }
        }
      }
    ).catch(
      (e) => {
        console.log(e)
      }
    )
}
export const queryPendingCallSheet = ({commit, state, rootState, dispatch}, searchCondition) => { // 查询待处理的通话列表
  let type = searchCondition.type
  let searchCount = searchCondition.searchAllCount
  delete searchCondition.searchAllCount
  delete searchCondition.type
  return call.queryPendingCallSheet(searchCondition).then(response => {
    if (response.success) {
      if (searchCount) { // 通话查询count总数
        return response
      } else { // 普通查询
        commit(types.QUERY_CALL_LIST, {data: response, type}) // 存储查询到的通话列表：来电，待处理，全部
      }
    }
  }).catch((e) => {
    console.log(e)
  })
}
export const getPendingCallSheetCount = ({commit, state, rootState, dispatch}, query) => { // 查询待处理的通话列表
  let getQuery = query || {}
  return call.getPendingCallSheetCount(getQuery).then(response => {
    if (response.success) {
      let pendingText = ''
      if (response.more) {
        pendingText = '99+'
      } else {
        pendingText = response.count
      }
      commit(types.CALL_PENDING_NUMBERS, pendingText)
    }
  }).catch((e) => {
    console.log(e)
  })
}
export const queryCallListCount = ({commit, state, rootState, dispatch}, searchCondition) => { // 通话批量操作时查询下当前条件下的通话总条数
  delete searchCondition.phoneBar
  delete searchCondition.type
  return call.queryCallList(searchCondition)
    .then(
      response => {
        return response
      }
    ).catch(
      (e) => {
        console.log(e)
        // 'message.default_tips'
      }
    )
}
/*
 点击某条通话记录后触发的action
 */
export const getSelectedCallInfo = ({commit, state, rootState}, {data, type}) => { // 获取技能组和满意度的数据
  let promises = []
  return getCache({commit, state: rootState}, {type: 'queues'}).then((queues) => {
    m7dicMap.updateCache('callQueues', queues) // 请求回来的技能组信息更新到dicMap中
    let investigate = m7dicMap.getCache('investigate')
    if (!investigate) { // 若是没有满意度调查，重新请求
      let p3 = call.findOneAppDic({name: '满意度调查选项'}).then(res => {
        if (res.success && res.data && res.data.options && Array.isArray(res.data.options)) {
          let data = []
          let options = res.data.options
          for (let i = 0; i < options.length; i++) {
            let name = options[i].name
            let value = options[i].options[0].name
            data.push({name, value})
          }
          m7dicMap.updateCache('investigate', data)
        } else {
          commit(globalTypes.SET_ERROR, 'message.default_tips')
        }
      })
      promises.push(p3)
    }
    return Promise.all(promises)
  })
}
/*
 通话详情模块的数据展示
 使用范围： 1.在线咨询的联系历史中的通话详情 2.在线咨询的工单信息中的通话详情 3.公共模板联系历史中的通话详情 4.公共模块的工单信息中的通话详情
 */
export const relocationCustomerAtTable = ({commit, state, rootState}, data) => {
  let userPower = rootState.session.user
  let self = data.self // 获取vue的this
  delete data.self
  let p0 = call.relocationCustomer(data)
  let p1 = getCache({commit, state: rootState}, {type: 'queues'})
  let p2 = getCache({commit, state: rootState}, {type: 'agents'})
  let p3 = getCache({commit, state: rootState}, {type: 'callType'})
  let p4 = getCache({commit, state: rootState}, {type: 'callStatus'})
  return Promise.all([p0, p1, p2, p3, p4]).then(([res]) => {
    if (res.success) {
      let list = res.row || {}
      // 处理座席
      let userName = ''
      if (list.DISPOSAL_AGENT && list.DISPOSAL_AGENT !== '') {
        let allAgent = self.$agentsMap() || {}
        let user = allAgent[list.DISPOSAL_AGENT]
        if (user) {
          userName = user.displayName + '[' + user.exten + ']'
        }
      }
      list.DISPOSAL_AGENT_show = userName
      // 呼叫类型
      let CONNECT_TYPE = ''
      if (getCacheByKey('callType', 'code_value', list.CONNECT_TYPE) != null) { // callType通话类型 eg: 普通来电，来电转接
        CONNECT_TYPE = getCacheByKey('callType', 'code_value', list.CONNECT_TYPE).code_name
      }
      if (list.CONNECT_TYPE != null) {
        if (list.CONNECT_TYPE === 'dialout' || list.CONNECT_TYPE === 'dialTransfer') {
          list.CALLED_NO_SHOW = checkHideTel(list.CALLED_NO, userPower)
          list.CALL_NO_SHOW = list.CALL_NO
        } else {
          list.CALLED_NO_SHOW = list.CALLED_NO
          list.CALL_NO_SHOW = checkHideTel(list.CALL_NO, userPower)
        }
      }
      list.CONNECT_TYPE_show = CONNECT_TYPE
      // 接听状态
      let STATUS = ''
      if (getCacheByKey('callStatus', 'code_value', list.STATUS) != null) { // callStatus 通话状态 eg： ivr, 已接听
        STATUS = getCacheByKey('callStatus', 'code_value', list.STATUS).code_name
      }
      list.STATUS_show = STATUS
      // 满意度
      let appraiseKey = list.INVESTIGATE ? list.INVESTIGATE : ''
      let options = m7dicMap.getCache('investigate')
      let satisfaction = ''
      for (let i = 0; i < options.length; i++) {
        if (appraiseKey === options[i].value) {
          satisfaction = options[i].name
          break
        }
      }
      if (!satisfaction) {
        satisfaction = appraiseKey || '' // 若字典配置被删除就默认显示数字eg:1
      }
      list.satisfaction = satisfaction
      list.INVESTIGATE_show = satisfaction
      // 呼叫时长
      let chatDuration = '00:00:00'
      if (list.BEGIN_TIME && list.END_TIME) {
        chatDuration = millsToDate(new Date(list.END_TIME).getTime() - new Date(list.BEGIN_TIME).getTime())
      }
      list.CALL_TIME_LENGTH_show = chatDuration
      list.queueTimeLen = getCallTimeLength(list.QUEUE_TIME_LENGTH)
      list.RING_TIME_LENGTH_show = getCallTimeLength(list.RING_TIME_LENGTH)
      let queueNameObj = getCacheByKey('queues', 'Exten', list.ERROR_MEMO)
      if (queueNameObj) {
        list.queueName = queueNameObj.DisplayName
      }
      if (list.MANYQUEUE_NUMBER) {
        let queueArr = list.MANYQUEUE_NUMBER.split(';') || []
        let queueArrName = ''
        for (let i = 0; i < queueArr.length; i++) {
          if (i > 0) {
            queueArrName += ' => '
          }
          let itemQueueName = getCacheByKey('queues', 'Exten', queueArr[i])// 处理技能组名称
          if (itemQueueName) {
            queueArrName += itemQueueName.DisplayName
          }
        }
        list.queueArrName = queueArrName
      } else {
        list.queueArrName = '--'
      }
      if (list.REPEAT_CALL) {
        list.repeatCall = list.REPEAT_CALL === '48h' ? m7Language('call.repeatCall48h') : m7Language('call.repeatCall24h')
      } else {
        list.repeatCall = '--'
      }
      return list
    } else {
      return false
    }
  })
}
export const queryLatestedCallSheet = ({commit, state, rootState}, {data, type}) => { // 因当前通话是重复来电故请求通话历史
  return call.queryLatestedCallSheet(data).then(resp => {
    if (resp && resp.success) {
      let list = resp.list
      for (let i = 0; i < list.length; i++) {
        let queueNameObj = getCacheByKey('queues', 'Exten', list[i].ERROR_MEMO)
        let callTypeObj = getCacheByKey('callStatus', 'code_value', list[i].STATUS)
        if (queueNameObj) {
          list[i].queueName = queueNameObj.DisplayName
        } else {
          list[i].queueName = '--'
        }
        if (callTypeObj) {
          list[i].STATUS_show = callTypeObj.code_name
        } else {
          list[i].STATUS_show = '--'
        }
        list[i].CALL_TIME_LENGTH_show = getCallTimeLength(list[i].CALL_TIME_LENGTH)
        list[i].queueTimeLen = getCallTimeLength(list[i].QUEUE_TIME_LENGTH)
        list[i].RING_TIME_LENGTH_show = getCallTimeLength(list[i].RING_TIME_LENGTH)
      }
      let count = resp.count || 0
      let allData = {'list': list, 'count': count}
      commit(types.QUERY_CALL_HISTORY, {data: allData, type}) // 存储重复来电的通话历史
    }
    return resp
  }).catch((e) => {
    console.log(e)
  })
}

export const relocationCustomer = ({commit, state, rootState}, {data, type}) => {
  return call.relocationCustomer({_id: data}).then(resp => {
    if (resp.success) {
      let relocationCustomerType
      if (resp.row.CUSTOMER_ID === '00000000000000000000') { // 000**00说明是未知客户或者是多个匹配客户
        if (resp.list.length > 1) { // 多个匹配客户
          relocationCustomerType = 'multi'
          let autoCust = {
            autoCustObj: {
              list: resp.list,
              count: resp.list.length || 0
            },
            autoCustLength: resp.list.length || 0
          }
          commit(types.SET_AUTO_CUST, {callSheetId: data, autoCust})
        } else if (resp.list.length === 1) {
          // 解决相同号码，一则通话记录绑定客户之后，其他相同号码记录点击卡片自动绑定客户（卡片和右侧实时更新）
          relocationCustomerType = 'one'
          resp.row.CUSTOMER_NAME = resp.list[0].name
          commit(types.UPDATE_CURRENT_CUSTOMER_INFO, {callId: resp.row.CALL_SHEET_ID, customer: resp.list[0]}) // 更新当前通话记录的客户信息
        } else {
          relocationCustomerType = 'none'
        }
      } else {
        if (resp.list.length === 0) {
          relocationCustomerType = 'deleted'
        } else {
          relocationCustomerType = 'one'
        }
      }
      commit(types.SET_CALL_INFO, {data: resp.row, type: type}) // 设置当前通话的通话信息
      commit(types.RELOCATION_CUSTOMER, {relocationCustomerType, type}) // 经搜索没用上，待验证
      // 来电  set current customer 多传一个 businessId
      if (relocationCustomerType === 'one') {
        commit(globalTypes.SET_CURRENT_CUSTOMER, { data: resp.list[0], type: 'call', tabType: type }) // 设置当前的客户信息，用于更新通话模块的客户组件
      } else {
        commit(globalTypes.SET_CURRENT_CUSTOMER, {data: null, type: 'call', tabType: type})
      }
    }
    return resp
  })
}
export const queryIvrContrail = ({ commit, state, rootState }, data) => { // ivr轨迹
  return call.queryIvrContrail(data).then(response => {
    return response
  }).catch(err => {
    console.error(err)
  })
}
/*
  查询转接轨迹
 */
export const queryTransferContrail = function({commit, state, rootState}, {data: callSheet, type}) {
  if (!callSheet) {
    return
  }
  if (callSheet.CONNECT_TYPE === 'transfer' || callSheet.CONNECT_TYPE === 'dialTransfer') { // 通话类型为转接或者是外呼转接
    let transferRecords = []
    let p1 = getCache({commit, state: rootState}, {type: 'agents'})
    let p2 = getCache({commit, state: rootState}, {type: 'queues'})
    let p = Promise.all([p1, p2])
    return p.then(([agents, skillgroups]) => {
      let getTransferRecord = function (callRecordId) {
        let transferRecord = {transferFrom: '', transferAction: '', transferTo: '', beginTime: ''}
        call.getCdrInfo(callRecordId).then(res => {
          if (res.data) {
            transferRecord.beginTime = res.data.BEGIN_TIME ? res.data.BEGIN_TIME : ''
          }
          if (res.success && res.data && res.data.TRANSFER_MODE && res.data.TRANSFER_NUM && res.data.TRANSFER_AGENT && res.data.DISPOSAL_AGENT && res.data.REF_CALL_SHEET_ID && res.data.CALL_SHEET_ID !== res.data.REF_CALL_SHEET_ID) {
            transferRecord.transferFrom = getAgentName(agents, res.data.TRANSFER_AGENT) + '[' + res.data.TRANSFER_AGENT + ']' // 转接自**
            if (res.data.TRANSFER_MODE === 'skillgroup') { // 转技能组
              transferRecord.transferAction = getSkillGroupName(skillgroups, res.data.TRANSFER_NUM)
            } else if (res.data.TRANSFER_NUM.length < 5) { // 转坐席
              transferRecord.transferAction = getAgentName(agents, res.data.TRANSFER_NUM) + '[' + res.data.TRANSFER_NUM + ']'
            } else {
              transferRecord.transferAction = res.data.TRANSFER_NUM
            }
            if (res.data.TRANSFER_MODE === 'num' && res.data.TRANSFER_NUM.length > 5) { // 转外线
              transferRecord.transferTo = res.data.TRANSFER_NUM // 转接给**
            } else {
              let allAgentObj = m7dicMap.getCache('agentObj')
              let curAgentObj = allAgentObj[res.data.DISPOSAL_AGENT] ? allAgentObj[res.data.DISPOSAL_AGENT] : null
              if (curAgentObj) {
                transferRecord.transferTo = curAgentObj.displayName + '[' + curAgentObj.exten + ']'
              }
            }
            transferRecords.push(transferRecord)
            getTransferRecord(res.data.REF_CALL_SHEET_ID)
          } else if (res.success) {
            commit(types.QUERY_TRANSFER_CONTRAIL, {transferRecords, type}) // 转接轨迹的数据 array
          } else {
            commit(globalTypes.SET_ERROR, 'message.getTransferRecordFail')
          }
        }).catch((e) => {
          console.log(e)
        })
      }
      getTransferRecord(callSheet._id)
    }).catch((e) => {
      console.log(e)
    })
  }
}
/*
 提交批量导出录音任务触发的action
 */
export const addExportMonitorTask = ({commit}, data) => {
  return call.addExportMonitorTask(data)
    .then(
      response => {
        // if (!response.success) {
        //   commit(globalTypes.SET_ERROR, 'message.submitFail')
        // }
        return response
      }
    ).catch(
      (e) => {
        console.log(e)
      }
    )
}
/*
  点击 导出 触发的action
*/
export const exportCdrExcel = ({commit}, {data, type}) => {
  return call.exportCdrExcel(data)
    .then(
      response => {
        if (response.Succeed) {
          commit(globalTypes.SET_FILEDOWNLOAD, {path: response.path, isSession: true})
        } else {
        }
      }
    ).catch(
      (e) => {
        console.log(e)
      }
    )
}
/*
  修改备注触发的action
*/
export const saveCdrMemo = ({commit}, {data, type, currentCallId}) => {
  return call.saveCdrMemo(data)
    .then(
      response => {
        if (response.success) {
          if (data.CALL_SHEET_ID === currentCallId) { // 当前卡片上编辑的记录和右侧已点开的记录是同一个通话记录，要做实时同步
            commit(types.SAVE_CDR_MEMO, {memo: data.memo, type})
          }
          commit(globalTypes.SET_SUCCESS, 'saveEditSucess')
        } else {
          commit(globalTypes.SET_ERROR, 'message.memoFail')
        }
      }
    ).catch(
      (e) => {
        console.log(e)
      }
    )
}

/*
  添加,删除通话标签触发的action
*/
export const markCallSheet = ({commit}, {data, type}) => {
  return call.markCallSheet(data)
    .then(
      response => {
        if (response.success) {
          return true
        } else {
          commit(globalTypes.SET_ERROR, 'message.default_tips')
          return false
        }
      }
    ).catch(
      (e) => {
        console.log(e)
      }
    )
}
/*
  查看通话标签操作日志触发的action
*/
export const getCallLabelOPHistory = ({commit}, {data, type}) => {
  return call.getCallLabelOPHistory(data)
    .then(
      response => {
        return response
      }
    ).catch(
      (e) => {
        console.log(e)
      }
    )
}

/*
保存黑名单
*/
export const saveBlackList = ({commit, rootState, dispatch}, {data}) => {
  let promises = []
  return Promise.all([
    getCache({commit, state: rootState}, {type: 'inBlackList'}),
    getCache({commit, state: rootState}, {type: 'outBlackList'})
  ]).then(([inBlackList, outBlackList]) => {
    // 判断是否存在黑名单中
    let arr = inBlackList.filter(item => {
      return item.BlackNum === data.BlackNum
    })
    let arr1 = outBlackList.filter(item => {
      return item.BlackNum === data.BlackNum
    })
    // 当type为3时特殊处理
    if (data.phoneType === '3') {
      if (arr.length > 0 && arr1.length > 0) {
        if (data.Type === '1') {
          commit(globalTypes.SET_ERROR, 'call.blackNumExisted')
        }
      } else if (arr.length > 0 && arr1.length <= 0) {
        if (data.Type === '2') {
          return data
        }
      } else if (arr.length <= 0 && arr1.length > 0) {
        if (data.Type === '1') {
          return data
        }
      } else {
        return data
      }
    } else {
      if (arr.length > 0 && data.Type === '1') {
        commit(globalTypes.SET_ERROR, 'call.blackNumExisted')
      } else if (arr1.length && data.Type === '2') {
        commit(globalTypes.SET_ERROR, 'call.blackNumExisted')
      } else {
        return data
      }
    }
  }).then(response => {
    if (response) {
      call.saveBlackList(data).then(response => {
        if (response.success) {
          if (data.Type === '1') {
            getCache({commit, state: rootState}, {type: 'inBlackList'}).then(list => { // 把当前数据插入更IvrMap中黑名单中
              list.push(data)
            })
          } else {
            getCache({commit, state: rootState}, {type: 'outBlackList'}).then(list => { // 把当前数据插入更IvrMap中黑名单中
              list.push(data)
            })
          }
          commit(globalTypes.SET_SUCCESS, 'call.successAddBlack')
          let p1 = call.reloadIvr(response.data) // 重新加载ivrMap的数据
          promises.push(p1)
          return Promise.all(promises)
        } else {
          commit(globalTypes.SET_ERROR, 'call.failAddBlack')
        }
      })
    }
  })
}

/*
    移除通话标记
 */
export const removeKeyTag = ({commit}, data) => {
  return call.removeKeyTag(data)
    .then(
      response => {
        if (response.success) {
          commit(globalTypes.SET_SUCCESS, 'call.removeKeyTagSuc')
        } else {
          commit(globalTypes.SET_ERROR, 'message.removeTagFail')
        }
      }
    ).catch(
      (e) => {
        console.log(e)
      }
    )
}
/*
    离线转写
 */
export const offonlineTrans = ({commit}, data) => {
  return call.offonlineTrans(data)
    .then(
      response => {
        if (response.success) {
          return response
        }
      }
    ).catch(
      (e) => {
        console.log(e)
      }
    )
}
/*
    来电后触发此action
   来电弹屏对接兼容：
   **历史：cc的来电对接中的对接工单和对接url是柔和在一个select的，并且只能选择一个。
          新版是对接工单和对接url拆分为2个select并且对接url最多可以选择2个。
   **代码兼容： KfBussinessTypeId是判断是kf还是cc入库的关键值，cc一直取旧的配置，代码没动，kf只要一保存配置，cc后面怎么改都不会影响kf的配置
            若kf从来没有入库过，没有KfBussinessTypeId，会默认取cc的旧配置
 */
export const callItemAdd = ({commit, state, rootState}, data) => {
  commit('call/CURRENT_TRANS_ID', {callSheetId: data.callSheetId, type: 'cdr_call'})
  let callTabArr = window.sessionStorage.getItem('callTabParameter')
  callTabArr = callTabArr ? JSON.parse(callTabArr) : []
  callTabArr.push({'id': data.callSheetId, 'data': data})
  window.sessionStorage.setItem('callTabParameter', JSON.stringify(callTabArr)) // 来电tab对接的参数
  data.unRead = true
  let promises = [
    getCache({commit, state: rootState}, {type: 'agents'}),
    getCache({commit, state: rootState}, {type: 'queues'}),
    getCache({commit, state: rootState}, {type: 'callUrls'})]
  if (rootState.session.account.tokenCheck) { // 有获取token的权限
    promises.push(userApi.getTokenId())
  }
  Promise.all(promises).then(([agents, skillgroups, callUrls, token]) => {
    // 来电对接 3个类别 内嵌，tab ,new window
    let isKfCdrInterface = false   //  新版  或   老版的  来电对接
    let BussinessTypeId = ''
    let CallinTypeId = []
    for (let u = 0; u < skillgroups.length; u++) {
      if (data.queue === skillgroups[u].Exten) {
        if (typeof (skillgroups[u].KfBussinessTypeId) === 'undefined') { // 老版入库
          isKfCdrInterface = false
          BussinessTypeId = skillgroups[u].BussinessTypeId.split('_')[1]
        } else { // kf入库
          BussinessTypeId = skillgroups[u].KfBussinessTypeId.split('_')[1]
          CallinTypeId = skillgroups[u].CallinTypeId
          isKfCdrInterface = true
        }
        break
      }
    }
    let arr = JSON.parse(window.sessionStorage.getItem('callBussinessTypeId')) || []
    arr.push({'id': data.callSheetId, 'businessTypeId': BussinessTypeId})
    window.sessionStorage.setItem('callBussinessTypeId', JSON.stringify(arr))
    if (!isKfCdrInterface) {   //   老版来电对接处理
      if (BussinessTypeId) {
        for (let y = 0; y < callUrls.length; y++) {
          if (callUrls[y]._id === BussinessTypeId) {
            let url = ArrangeUrl(data, callUrls[y], rootState, token)
            let localArr = JSON.parse(window.sessionStorage.getItem('callIframeUrl')) || []
            let newUrl = ''
            if (callUrls[y].type === '1') {
              newUrl = url
              localArr.push({callSheetId: data.callSheetId, url: [{urlItem: newUrl, name: callUrls[y].name}]})
            } else if (callUrls[y].type === '2' && callUrls[y].outOpenType === 'tab') {
              window.open(url)
            } else if (callUrls[y].type === '2' && callUrls[y].outOpenType === 'win') {
              window.open(url, '_blank', 'toolbar=0,location=0,menubar=0')
            }
            window.sessionStorage.setItem('callIframeUrl', JSON.stringify(localArr))
            break
          }
        }
      }
    } else {   //   新版来电对接处理
      if (CallinTypeId && CallinTypeId.length > 0) {
        let urlArr = []  //  来电对接的url数组
        for (let m = 0; m < CallinTypeId.length; m++) {
          for (let y = 0; y < callUrls.length; y++) {
            if (callUrls[y]._id === CallinTypeId[m].split('_')[1]) {
              let url = ArrangeUrl(data, callUrls[y], rootState, token)
              let newUrl = ''
              if (callUrls[y].type === '1') {
                if (callUrls[y].businesses && callUrls[y].businesses.length > 0) {
                  callUrls[y].businesses.forEach(item => {
                    let itemUrl = ArrangeUrl(data, item, rootState, token)
                    urlArr.push({name: item.name, urlItem: itemUrl})
                  })
                } else {
                  newUrl = url
                  urlArr.push({urlItem: newUrl, name: callUrls[y].name})
                }
              } else if (callUrls[y].type === '2' && callUrls[y].outOpenType === 'tab') {
                window.open(url)
              } else if (callUrls[y].type === '2' && callUrls[y].outOpenType === 'win') {
                window.open(url, '_blank', 'toolbar=0,location=0,menubar=0')
              }
              break
            }
          }
        }
        let localArr = JSON.parse(window.sessionStorage.getItem('callIframeUrl')) || []
        localArr.push({callSheetId: data.callSheetId, url: urlArr})
        window.sessionStorage.setItem('callIframeUrl', JSON.stringify(localArr))
      }
    }
    if (!data.ivrkey) {
      data.ivrkey = ''
    }
    if (!data.queueName) {
      data.queueName = ''
    }
    if (data.data && data.data.TransferMode && data.data.TransferNum && data.data.TransferAgent) {
      data.TransferMode = data.TransferMode || data.data.TransferMode
      data.TransferNum = data.TransferNum || data.data.TransferNum
      data.TransferAgent = data.TransferAgent || data.data.TransferAgent
    }
    if (data && data.WaitTimeOut && data.transferFromWhenWaitTimeout && data.transferToWhenWaitTimeout && data.transferModeWhenWaitTimeout) {
      data.waitTimeOut = data.WaitTimeOut
      data.transferFromWhenWaitTimeout = data.transferFromWhenWaitTimeout
      data.transferToWhenWaitTimeout = data.transferToWhenWaitTimeout
      data.transferModeWhenWaitTimeout = data.transferModeWhenWaitTimeout
      let transferFromWhenWaitTimeoutNum = getSkillGroupName(skillgroups, data.transferFromWhenWaitTimeout)
      let transferToWhenWaitTimeoutNum = ''
      if (data.transferModeWhenWaitTimeout === 'User') { // 到座席
        transferToWhenWaitTimeoutNum = getAgentName(agents, data.transferToWhenWaitTimeout) + '[' + data.transferToWhenWaitTimeout + ']'
      } else {
        transferToWhenWaitTimeoutNum = getSkillGroupName(skillgroups, data.transferToWhenWaitTimeout)
      }
      data.transferFromWhenWaitTimeoutNum = transferFromWhenWaitTimeoutNum
      data.transferToWhenWaitTimeoutNum = transferToWhenWaitTimeoutNum
    }
    if (data.TransferMode && data.TransferNum && data.TransferAgent) {
      let transferTo = ''
      let transferFrom = ''
      transferFrom = getAgentName(agents, data.TransferAgent) + '[' + data.TransferAgent + ']'
      if (data.TransferMode === 'skillgroup') {
        transferTo = getSkillGroupName(skillgroups, data.TransferNum)
      } else {
        transferTo = getAgentName(agents, data.TransferNum) + '[' + data.TransferNum + ']'
      }
      data.transferFrom = transferFrom
      data.transferTo = transferTo
    }
  }).then(() => {
    customerApi.queryCustomerList({phone: data.originCallNo}).then(response => {
      if (response.success) {
        if (response.list.length < 1) { // 未知客户
          data.CUSTOMER_TYPE = 'unk'
          if (rootState.session.account.autoSave) {
            // 客户配置--》自动保存未定位到的客户
            generateUnkCustomerInfo(data, {commit, state, rootState}).then((addCustomerData) => { // 生成未知客户的信息
              customerApi.addCustomer(addCustomerData).then(res1 => { // 根据生成的信息，添加客户
                if (res1.success && res1.data) { // 添加客户成功后更新客户信息
                  commit(types.UPDATE_CURRENT_CUSTOMER_INFO, {customer: res1.data, callId: data.callSheetId})
                }
              })
            })
          }
        } else if (response.list && response.list.length === 1) { // 只有一个客户

          data.CUSTOMER_ID = response.list[0]._id
          data.CUSTOMER_STATUS = response.list[0].status
          data.CUSTOMER_NAME = response.list[0].name
          data.CUSTOMER_TYPE = 'one'
          if (response.list[0] && response.list[0].phone.length > 1) {
            response.list[0].phone.forEach(item => {
              if (item.tel === data.originCallNo) {
                data.CUSTOMER_MEMO = item.memo || ''
                return false
              }
            })
          } else {
            data.CUSTOMER_MEMO = response.list[0] && response.list[0].phone[0] ? response.list[0].phone[0].memo : ''
          }
          customerApi.queryCustomerInfo({_id: response.list[0]._id}).then(res1 => { // 查询客户信息
            if (res1.success && res1.data) { // 根据callSheetId更新cdr_call的客户信息
              commit(types.SET_CUSTOMER_INFO, {data: res1.data, callSheetId: data.callSheetId})
            }
          })
        } else if (response.list && response.list.length > 1) { // 多个匹配客户
          data.CUSTOMER_TYPE = 'multi'
          let autoCust = {
            autoCustObj: {
              list: response.list,
              count: response.list.length || 0
            },
            autoCustLength: response.list.length || 0
          }
          commit(types.SET_AUTO_CUST, {callSheetId: data.callSheetId, autoCust}) // 用于展示右侧详情中"定位到多个客户&选择一个客户"同个组件涉及其他模块的展示，此数据为标志值
        }
        commit(types.PUSH_CDR_CALL, data) // 往通话来电列表添加数据
        commit(types.PUSH_CURRENT_CDR_CALL, data) // 当前通话的客户信息
        commit(types.SET_STORAGE_CALLLIST) // 把来电list数据存储到sessionStorage，用于刷新系统后来电列表的重新展示
        commit(types.COUNT_UNREAD_CDR) // 计算未读来电数
        let notify = {
          tag: 'cdr',
          id: data.callSheetId,
          NOcallnum: 1,
          random: Math.random()
        }
        commit(globalTypes.SET_NOTIFY, notify) // 来电提醒
      }
      if (data.CONNECT_TYPE === 'normal') { // 普通来电类型查询当前来电是否是重复来电
        call.getRepeatOfCall({ CALL_NO: data.originCallNo }).then(res => {
          if (res && res.repeat) {
            commit(types.UPDATE_REPEAT_CALL, {callSheetId: data.callSheetId, repeat: res.repeat})
          }
        })
      }
    }).catch((e) => {
      console.log(e)
    })
  })
}
function getAgentName (agents, exten) { // 根据工号获取坐席名字
  for (let i = 0; i < agents.length; i++) {
    if (agents[i].exten === exten) {
      return agents[i].displayName
    }
  }
}
function getSkillGroupName (skillgroups, exten) {
  for (let j = 0; j < skillgroups.length; j++) {
    if (skillgroups[j].Exten === exten) {
      return skillgroups[j].DisplayName
    }
  }
}
function ArrangeUrl (data, callUrlsIndex, rootState, token) { // 来电弹屏url数据拼接
  let account = rootState.session.account
  if (!data.ivrkey) { // 参考cc补充之前对接缺失的字段
    data.ivrkey = ''
  }
  if (data.offeringTime) {
    let _t = formatShortTime(data.offeringTime)
    data.shortTime = _t.name
  } else {
    data.shortTime = ''
  }
  let Symbol = '&'
  if (callUrlsIndex.url.indexOf('?') === -1) {
    Symbol = '?'
  }
  let dataStr = ''
  for (let item in data) { // data 为事件中推送过来的参数，比如： 变量管理中的变量勾选为弹屏变量（注意： 弹屏变量的设置必须有双下滑线，否则不会推送）
    if (account.encryptionCheck && (item === 'originCallNo' || item === 'originCalledNo')) {
      if (account.encryType === 'aes') { // aes加密
        dataStr += item + '=' + getAesEncrypt(account.aesSecret, account.aesOffsetValue, data[item]) + '&'
      } else { // 默认加密
        let secretKey = account.secretKey
        dataStr += item + '=' + encrypt(secretKey, data[item]) + '&'
      }
    } else {
      dataStr += item + '=' + data[item] + '&'
    }
  }
  // 截取最后一个&
  dataStr = dataStr.slice(0, dataStr.length - 1)
  let url = callUrlsIndex.url
  let message = ''
  message += Symbol + dataStr + '&loginName=' + rootState.session.user.loginName + '&accountId=' + rootState.session.account.account
  if (token && token.token && token.tokenId) {
    message += '&token=' + token.token + '&tokenId=' + token.tokenId
  }
  if (url.indexOf('power.7moor.com') > -1 || url.indexOf('power-') > -1) {
    if (rootState.session.sessionId && window.sessionStorage.getItem('loginToken')) {
      message += '&sessionId=' + rootState.session.sessionId + '&loginToken=' + window.sessionStorage.getItem('loginToken')
    }
  }
  if (account.encryptionCheck && account.encryType === 'aes') { // 开启隐私加密 && aes加密
    message += `&${account.aesOffsetKey || 'iv'}=${account.aesOffsetValue}`
  }
  if (message.indexOf('#') !== -1) { // 转码参数里面的#，客户配置的url中带#不转码
    message = message.replace(/#/g, '%23')
  }
  url += message
  return url
}

export const callItemPush = ({commit, state, rootState}, data) => {
  commit(types.SET_CALL_LIST_PUSH, data)
}

export const callScreenLocationCustomer = ({commit, state, rootState}, data) => {
  return call.callScreenLocationCustomer(data).then(res => {
  }).catch(
    (e) => {
      console.log(e)
    }
  )
}
// 选择已存在客户
export const callLocationCustomer = ({commit, state}, data) => {
  // data
  /* customerId:,
   callId:,
   custName:,
   phone: */
  let callInfo = {}
  let customerPhone = ''
  if (state.current[data.submenu].callInfo && state.current[data.submenu].callInfo._id === data.callId) {
    callInfo = state.current[data.submenu].callInfo && state.current[data.submenu].callInfo // 取当前通话的通话信息
  }
  if (callInfo.CONNECT_TYPE === 'normal' || callInfo.CONNECT_TYPE === 'transfer') { // 来电或者是转接的通话取主叫
    customerPhone = callInfo.CALL_NO
  } else { // 其他情况取被叫
    customerPhone = callInfo.CALLED_NO
  }
  if (data.customer && data.customer.phone && data.customer.phone.length > 0) { // 合并的客户有手机号时
    let exists = false
    data.customer.phone.forEach(function (obj) {
      if (obj.tel === customerPhone) { // 判断下当前号码是否存在
        exists = true
      }
    })
    if (!exists) { // 若是不存在再push,存在的情况不用再次push
      data.customer.phone.push({tel: customerPhone, memo: ''})
    }
  } else if (data.customer && data.customer.phone && data.customer.phone.length <= 0) { // 若合并的客户没有手机号，把当前通话记录中的号码入库
    data.customer.phone.push({tel: customerPhone, memo: ''})
  }
  let postData = {}
  postData.customerId = data.customerId
  postData.callId = data.callId
  postData.custName = data.custName
  postData.phone = data.customer.phone
  if (data.dealSrc) {
    postData.dealSrc = data.dealSrc
  }
  commit(types.UPDATE_CURRENT_CUSTOMER_INFO, data) // 更新当前通话记录的客户信息
  return call.locationCustomer(postData).then(res => {
    return res
  })
}
export const callLocationCustomer2Add = ({commit, state}, data) => { // 来电新增客户 && 通话详情中添加客户
  if (data.type) {
    delete data.type
  }
  if (data.tabType) {
    delete data.tabType
  }
  return customerApi.addCustomer(data).then(res => {
    if (res.success && res.data) {
      commit(types.UPDATE_CURRENT_CUSTOMER_INFO, {callId: data.callId, customer: res.data}) // 更新当前通话记录的客户信息
    }
    return res
  })
}
function generateUnkCustomerInfo (data, {commit, state, rootState}) { // 生成未知客户的数据，用于来电自动保存客户
  return new Promise(function (resolve, reject) {
    let customer = {}
    let promises = [
      getCache({commit, state: rootState}, {type: 'custTmpls'}),
      getCache({commit, state: rootState}, {type: 'options', id: 'd7b9c68a-b50f-21d1-d5fd-41ea93f5f49c'})
    ]
    Promise.all(promises).then(
      ([custTmpls, provinceCache]) => {
        customer.dbType = custTmpls[0]._id
        let list = provinceCache.options
        for (let i = 0; i < list.length; i++) {
          if (list[i].name === data.callerProvince) {
            customer.province = list[i].key
            let cityList = list[i].options
            for (let j = 0; j < cityList.length; j++) {
              if (cityList[j].name === data.callerCity) {
                customer.city = cityList[j].key
                break
              }
            }
            break
          }
        }
        customer.callTel = data.originCallNo
        customer.callId = data.callSheetId
        customer.name = m7Language('public.unknownCustomer')
        customer.status = 'status0'
        customer.custsource1 = ''
        customer.title = ''
        customer.address = ''
        customer.note = ''
        customer.web = ''
        customer.categoryId = 'NA'
        customer.owner = rootState.session.user._id
        customer.category = ''
        customer.dealSrc = 'popup'
        customer.email = []
        customer.weixin = []
        customer.actionType = 'self'
        let phoneObj = {tel: data.originCallNo, memo: ''}
        customer.phone = [phoneObj]
        customer.attaches = []
        resolve(customer)
      }
    )
  }).catch(
    (e) => {
      console.log(e)
    }
  )
}
// export const callUpdateCustomer = ({ commit, state, rootState }, {callId, customer}) => { // 经搜索没用上，稳定后可删除
//   return customerApi.updateCustomer(customer)
//     .then(response => {
//       if (!response.success) {
//         return false
//       } else {
//         commit(types.UPDATE_CURRENT_CUSTOMER_INFO, {callId: callId, customer: customer})
//         return customerApi.queryCustomerInfo({ _id: customer._id })
//       }
//     })
//     .catch(err => {
//       console.error(err)
//       // 'message.default_tips'
//     })
// }
/**
 * 未处理通话记录标记为已处理
 * @param {Object} data
 * @param {String} data._id 通话id
 * @param {String} data.PROCESS_STATUS 已处理solved
 */
export const changeCallSheetProccessStatus = ({ commit, state, rootState }, data) => {
  return call.changeCallSheetProccessStatus(data)
    .then(response => {
      if (response.success) {
        commit(globalTypes.SET_SUCCESS, 'call.removePendingSuccess')
        return response
      } else {
        commit(globalTypes.SET_ERROR, 'message.default_tips')
      }
    })
    .catch(err => {
      console.error(err)
    })
}

export const getCallSheetLeakTable = ({ commit, state, rootState }, data) => { // 未接来电管理，查询列表数据 && 获取所有count && 分配当前所查询的
  return call.queryUnassignMissedCall(data)
    .then(response => {
      // 如果没有list字段 即是请求真实count的请求
      if (response.success && response.list) {
        let list = response.list
        let tableData = []
        tableData = list.map(val => {
          let _id = val._id
          let customerName = val.CUSTOMER_NAME
          let callNo = val.CALL_NO
          let newCalledNo = val.CALLED_NO
          let assginType = val.CALLBACK_AGENT ? m7Language('call.assgin') : m7Language('call.unassgin')
          let status = val.STATUS
          let OWNER_INFO = val.OWNER_INFO || '--'
          let callbackAgent = val.CALLBACK_AGENT
          let errorMemo = val.ERROR_MEMO
          let newOfferingTime = val.OFFERING_TIME
          let callBackAgentName = '--'
          let queues = m7dicMap.getCache('queues') || []
          let QUEUE_NAME = ''
          for (let i in queues) {
            if (queues[i].Exten === val.ERROR_MEMO) {
              QUEUE_NAME = queues[i].DisplayName
              break
            }
          }
          if (val.CALLBACK_AGENT) {
            let m7Obj = m7dicMap.getCache('agentObj')[val.CALLBACK_AGENT]
            callBackAgentName = m7Obj ? m7Obj.displayName + '[' + m7Obj.exten + ']' : ''
          }
          return {
            _id,
            customerName,
            callNo,
            newCalledNo,
            assginType,
            status,
            callbackAgent,
            errorMemo,
            newOfferingTime,
            callBackAgentName,
            OWNER_INFO,
            QUEUE_NAME
          }
        })
        if (response.more) { // 多于**条
          return {
            tableData,
            more: response.more,
            count: response.count
          }
        } else {
          return {
            tableData,
            count: response.count
          }
        }
      } else {
        return response
      }
    })
    .catch(err => {
      console.error(err)
    })
}

// export const confirmDelAllCdr = ({ commit, state, rootState }, data) => { // 删除查询到的未接来电记录，此功能被砍
//   return call.confirmDelAllCdr(data)
//     .then(response => {
//       if (response.success) {
//         console.log(3)
//       }
//     })
// }

// export const saveAssignCallBackAgent = ({ commit, state, rootState }, {data}) => { // 经搜索没用上，稳定后可删除
//   return call.saveAssignCallBackAgent(data)
//     .then(response => {
//       if (!response.success) {
//         commit(globalTypes.SET_ERROR, 'message.assignFail')
//         return false
//       } else {
//         return response
//       }
//     })
//     .catch(err => {
//       console.error(err)
//       // 'message.default_tips'
//     })
// }
export const showMissedCallInfo = ({ commit, state, rootState }, data) => { // 查看未接详情（未接来电管理中的查看详情）
  return call.showMissedCallInfo(data)
    .then(response => {
      if (!response.success) {
        return false
      } else {
        return response
      }
    })
    .catch(err => {
      console.error(err)
    })
}
export const assignMissedCall = ({ commit, state, rootState }, data) => { // 未接来电管理：分配当前所选的
  return call.assignMissedCall(data)
    .then(response => {
      if (!response.success) {
        return false
      } else {
        return response
      }
    })
    .catch(err => {
      console.error(err)
    })
}
export const assignMatchedMissedCall = ({ commit, state, rootState }, data) => { // 未接来电管理：分配当前所查询的
  return call.assignMatchedMissedCall(data)
    .then(response => {
      if (!response.success) {
        return false
      } else {
        return response
      }
    })
    .catch(err => {
      console.error(err)
    })
}
export const addMissedCDRExportTask = ({ commit, state, rootState }, data) => { // 未接来电管理：导出未接来电的任务
  return call.addMissedCDRExportTask(data).then(response => {
    return response
  }).catch(err => {
    console.error(err)
  })
}
export const commentCallSheetThroughCall = ({ commit, state, rootState }, data) => { // 来电卡片正在通话中打备注
  return call.commentCallSheetThroughCall(data, rootState)
    .then(response => {
      if (!response.success) {
        commit(globalTypes.SET_ERROR, 'call.addLabelFail')
        return false
      } else {
        commit(globalTypes.SET_SUCCESS, 'saveEditSucess')
        return response
      }
    })
    .catch(err => {
      console.error(err)
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
  /*
    * data {}
    * data.BEGIN_TIME 起始时间
    * data.END_TIME   结束时间
    * data.pageSize   每页的条数
    * data.page       请求页数
  */
export const queryExportMonitorTask = ({ commit, state, rootState }, data) => { // 导出录音任务list查询
  return call.queryExportMonitorTask(data)
    .then(response => {
      if (!response.success) {
        commit(globalTypes.SET_ERROR, 'message.searchFail')
        return false
      } else {
        return response
      }
    })
    .catch(err => {
      console.error(err)
    })
}
/*
 * data {}
 * data.BEGIN_TIME 起始时间
 * data.END_TIME   结束时间
 * data.pageSize   每页的条数
 * data.page       请求页数
 */
export const getCallSheetExportTaskList = ({ commit, state, rootState }, data) => { // 通话记录导出任务list查询
  return call.getCallSheetExportTaskList(data)
    .then(response => {
      if (!response.success) {
        commit(globalTypes.SET_ERROR, 'message.searchFail')
        return false
      } else {
        return response
      }
    })
    .catch(err => {
      console.error(err)
    })
}
export const deleteCallSheetExportTask = ({ commit, state, rootState }, data) => { // 通话导出记录任务： 取消任务
  return call.deleteCallSheetExportTask(data)
    .then(response => {
      if (!response.success) {
        commit(globalTypes.SET_ERROR, 'message.cancelTaskFail')
        return false
      } else {
        return response
      }
    })
    .catch(err => {
      console.error(err)
    })
}
export const addCallSheetExportTask = ({ commit, state, rootState }, data) => { // 通话批量操作导出记录大于1W条新增一条导出任务
  return call.addCallSheetExportTask(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}

export const addCallOfflineTranscriptionTask = ({ commit, state, rootState }, data) => { // 通话批量操作导出记录大于1W条新增一条导出任务
  return call.addCallOfflineTranscriptionTask(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
  /*
    * data id 取消导出录音任务的id
  */
export const removeExportMonitorTask = ({ commit, state, rootState }, data) => {
  return call.removeExportMonitorTask(data)
    .then(response => {
      if (!response.success) {
        commit(globalTypes.SET_ERROR, 'message.cancelTaskFail')
        return false
      } else {
        return response
      }
    })
    .catch(err => {
      console.error(err)
    })
}
export const submitAppealCall = ({ commit, state, rootState }, data) => { // 质检申诉
  return call.submitAppealCall(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
export const getTranslationRecord = ({ commit, state, rootState }, data) => {
  return call.getTranslationRecord(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
export const getWordSegmentation = ({ commit, state, rootState }, data) => {
  return call.getWordSegmentation(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
export const updateTranslationState = ({ commit, state, rootState }, data) => {
  return call.updateTranslationState(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
// 质检中 通话录音是否自动播放  ======
export const callRecordAutoPlay = ({ commit, state, rootState }, data) => {
  return call.callRecordAutoPlay(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
/***********************金牌话术相关接口***********************/
//检查账⼾是否启⽤了智能话务辅助功能
export const checkStatus = ({commit, state, rootState},data) => {
  return call.checkStatus(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
//根据座席或技能组ID获取话术流程
export const queryDiscourse = ({commit, state, rootState},data) => {
  return call.queryDiscourse(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
  //根据话术导航ID获取流程信息
export const getScriptFlowByID = ({commit, state, rootState},data) => {
  return call.getScriptFlowByID(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
//使⽤指定的话术流程
export const adoptScriptFlow = ({commit, state, rootState},data) => {
  return call.adoptScriptFlow(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
//话术导航历史
export const getScriptFlowHistory = ({commit, state, rootState},data) => {
  return call.getScriptFlowHistory(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}
//查询话术推荐列表
export const getScriptRecommendations = ({commit, state, rootState},data) => {
  return call.getScriptRecommendations(data)
    .then(response => {
      return response
    })
    .catch(err => {
      console.error(err)
    })
}

